<!-- subpkg_consult/payment/index.vue -->
<script lang="ts" setup>
import { preOrderApi } from "@/apis/consult";
import { createOrderApi, patientDetailApi } from "@/apis/patient";
import { orderPayApi } from "@/apis/user";
import { useConsultStore } from "@/stores/consult";
import type { CustomPaymentInstance } from "@/types/components";
// import { useConsultStore } from "@/stores/consult";
import type { OrderPreData } from "@/types/consult";
import type { PatientItem } from "@/types/patient";
import { ref } from "vue";

const store = useConsultStore();
console.log("支付页", store.type);
const preOrderInfo = ref<OrderPreData>();
const getData = async () => {
  const res = await preOrderApi({
    type: store.type, // 比传参数
    illnessType: store.illnessType,
  });
  preOrderInfo.value = res;
};

getData();

const patientInfo = ref<PatientItem>();
// 获取患者信息
const getPatientDetail = async () => {
  // 获取当前默认选中的患者信息
  const res = await patientDetailApi(store.patientId);
  // console.log(res)
  patientInfo.value = res;
};

getPatientDetail();

const onSubmit = async () => {
  const res = await createOrderApi({
    type: store.type,
    depId: store.depId,
    illnessType: store.illnessType,
    patientId: store.patientId,
    // 展开图文问诊表单收集的信息
    ...store.illnessInfo,
  });
  // console.log(res)
  // uni.showToast({ title: "订单id" + res.id, icon: "none" });
  
  // 保存订单 id ，传递给支付组件
  orderId.value = res.id;
  // 调用支付组件的方法，打开支付组件
  paymentRef.value?.open();
};

// 订单id
const orderId = ref("");
// 支付组件实例
const paymentRef = ref<CustomPaymentInstance>();

// 立即支付
const payNow = async (index: number) => {
  // 微信支付
  if (index === 0) {
    uni.showToast({ title: "暂未开通该支付方式", icon: "none" });
    return;
  }
  uni.showLoading({ title: '支付中...' })
    // 支付宝支付，参数发送给后端，后端生成支付 URL
    const res = await orderPayApi({
      orderId: orderId.value,
      paymentMethod: index,
      payCallback: 'http://localhost:5173/#/subpkg_consult/room/index',
    })
    uni.hideLoading()
  // #ifdef H5
  location.href = res.payUrl; // H5 端改变栏地址为支付 URL
  // #endif
};

// 关闭支付
const closePayment = async () => {
  const res = await uni.showModal({
    title: "关闭支付",
    content: "取消支付将无法获得医生回复，医生接诊名额有限，是否确认关闭？",
    cancelText: "仍要关闭",
    cancelColor: "#848484",
    confirmText: "继续支付",
    confirmColor: "#16C2A3",
  });
  if (res.confirm) {
    paymentRef.value?.close();
  }
  if (res.cancel) {
    // 关闭所有页面，去首页
    uni.reLaunch({ url: "/pages/my/index" });
    // 清空 store 信息
  store.clear();//先注释掉，方便测试
  }
};
</script>

<template>
  <scroll-view v-if="preOrderInfo">
    <view class="payment-page">
      <uni-section
        title-font-size="32rpx"
        title-color="#121826"
        padding="30rpx"
        :title="`图文问诊 ${preOrderInfo.payment}`"
      >
        <uni-list :border="false">
          <uni-list-item
            title="极速问诊"
            note="自动分配医生"
            thumb="/static/uploads/doctor-avatar.jpg"
            thumb-size="lg"
          />
          <uni-list-item
            title="优惠券"
            show-arrow
            :right-text="`-¥${preOrderInfo.couponDeduction}`"
          />
          <uni-list-item title="积分抵扣">
            <template #footer>
              <view class="uni-list-text-red">
                -¥{{ preOrderInfo.pointDeduction }}
              </view>
            </template>
          </uni-list-item>
          <uni-list-item title="实付款">
            <template #footer>
              <view class="uni-list-text-red"
                >¥{{ preOrderInfo.actualPayment }}</view
              >
            </template>
          </uni-list-item>
        </uni-list>
      </uni-section>

      <view class="dividing-line"></view>

      <uni-section
        title-font-size="32rpx"
        title-color="#121826"
        padding="30rpx"
        title="患者资料"
      >
        <uni-list :border="false">
          <uni-list-item title="患者信息">
            <template #footer>
              <view class="uni-list-text-gray">
                {{ patientInfo?.name }} | {{ patientInfo?.genderValue }} |
                {{ patientInfo?.age }}岁
              </view>
            </template>
          </uni-list-item>
          <uni-list-item
            border
            title="病情描述"
            :note="store.illnessInfo.illnessDesc"
          />
        </uni-list>
      </uni-section>

      <!-- <view class="payment-agreement">
        <radio color="#20c6b2" value="1" />
        我已同意<text style="color: #20c6b2">支付协议</text>
      </view> -->
    </view>
    <!-- 下一步操作 -->
    <view class="next-step">
      <view class="total-amount">
        合计: <text class="number">¥{{ preOrderInfo.actualPayment }}</text>
      </view>
      <button @click="onSubmit" class="uni-button">立即支付</button>
    </view>
    <!-- 全局支付组件 -->
    <custom-payment
      ref="paymentRef"
      :order-id="orderId"
      :amount="preOrderInfo.actualPayment"
      @confirm="payNow"
      @close="closePayment"
    />
  </scroll-view>
</template>

<style lang="scss">
@import "./index.scss";
</style>
